package com.dingshi.security;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.dingshi.security.api.ApiResult;
import com.dingshi.security.api.ApiReturnResultListener;
import com.dingshi.security.api.UserApi;
import com.dingshi.security.db.SettingLoader;
import com.dingshi.security.util.StringUtils;
import com.dingshi.security.util.Utils;
import com.dingshi.security.view.LoadDialog;

public class LoginActivity extends Activity implements OnClickListener {

	protected static final String TAG = "LoginActivity";
	protected static final int ID_LOADING = 2013;
	private EditText user_edit;
	private EditText pwd_edit;
	private Button btn_login;
	private LinearLayout btn_set;
	private ImageView btn_arrow;
	private EditText login_server_edit;
	private EditText update_server_edit;
	private LinearLayout item;
	private EditText svr_path;
	private EditText update_svr_path;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_orignal);
		initComponents();
		registerClick();
	}

	private void registerClick() {
		btn_login.setOnClickListener(this);
		btn_set.setOnClickListener(this);
		btn_arrow.setOnClickListener(this);

	}

	private void initComponents() {
		user_edit = (EditText) findViewById(R.id.editText1);
		pwd_edit = (EditText) findViewById(R.id.editText2);
		btn_login = (Button) findViewById(R.id.btn_login);
		btn_set = (LinearLayout) findViewById(R.id.btn_set);
		btn_arrow = (ImageView) findViewById(R.id.btn_arrow);
		login_server_edit = (EditText) findViewById(R.id.editText3);
		update_server_edit = (EditText) findViewById(R.id.editText4);

		item = (LinearLayout) findViewById(R.id.bottom_item);
		svr_path = (EditText)item.findViewById(R.id.editText3);
		update_svr_path = (EditText)item.findViewById(R.id.editText4);
		svr_path.setText(SettingLoader.getSvrPath(this));
		update_server_edit.setText(SettingLoader.getUpdateSvrPath(this));
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case ID_LOADING:
			LoadDialog dialog = new LoadDialog(this, "登录中。。。");
			return dialog;

		default:
			break;
		}
		return super.onCreateDialog(id);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
	}
	
	public void onAttachedToWindow() {
        this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);    
        super.onAttachedToWindow();
    }
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_HOME:
			Log.e("KeyCode", "home is click");
			return true;
		case KeyEvent.KEYCODE_BACK:
			
			return true;
		  case KeyEvent.KEYCODE_DPAD_LEFT: {  
	            return true;  
	        }  
	  
	        case KeyEvent.KEYCODE_DPAD_UP: {  
	            return true;  
	        }  
	  
	        case KeyEvent.KEYCODE_DPAD_RIGHT: {  
	            return true;  
	        }  
	  
	        case KeyEvent.KEYCODE_DPAD_DOWN: {  
	            return true;  
	        }  
	        case KeyEvent.KEYCODE_DPAD_CENTER: {  
	            return true;  
	        }  
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	
	private void savePath() {
		String svrpath = login_server_edit.getText().toString();
		String updatepath = update_svr_path.getText().toString();
		if(!Utils.isNullOrEmpty(svrpath)) {
			SettingLoader.setSvrPath(this,svrpath,updatepath);
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_login:
			savePath();
			String username = user_edit.getText().toString();
			String pwd = pwd_edit.getText().toString();
			if (StringUtils.isNullOrEmpty(username)) {
				Utils.showToast(this, "用户名不能为空");
				return;
			}
			if (StringUtils.isNullOrEmpty(pwd)) {
				Utils.showToast(this, "密码不能为空");
				return;
			}

			UserApi api = new UserApi(LoginActivity.this);
			api.setReturnResultListener(new ApiReturnResultListener() {

				@Override
				public <T> void onReturnSucceedResult(int requestCode,
						ApiResult<T> apiResult) {
					JSONObject jsonEntity = apiResult.getJsonEntity();
					if (jsonEntity != null) {
						// {"d":"双兴监控室","t":"1","r":"0","nid":"1","a":"双兴小区","n":"张三","did":"4","aid":"2"}
						// {"d":{"a":"双兴小区","aid":"2","d":"双兴监控室","did":"4","n":"张三","nid":"1","r":"0","t":"1",},"t":0}
						Log.e(TAG, "jsonEntity is " + jsonEntity.toString());
						try {
							int type = jsonEntity.getInt("t");
							switch (type) {
							case 0:// 对象
								JSONObject json = jsonEntity.getJSONObject("d");
								String result = json.getString("r");
								String userType = json.getString("t");//t标识用户类型 1报修，2维修
								
								if ("0".equals(result)) {
									Utils.showToast(LoginActivity.this, "登录成功");
									SettingLoader.setUserInfo(LoginActivity.this, json.toString());
									if("1".equals(SettingLoader.getGuardType(LoginActivity.this))) {
										SecurityApp.getApp(LoginActivity.this).nightShiftTimer();
									}
									Intent id = new Intent(LoginActivity.this,HomeActivity.class);
									id.putExtra("userType", userType);
									startActivity(id);
									finish();
									// 存储登录用户信息 TODO

								} else if ("-1".equals(result)) {
									Utils.showToast(LoginActivity.this, "密码错误");
								} else if ("-2".equals(result)) {
									Utils.showToast(LoginActivity.this, "账号不存在");
								}
								break;
							case 1:// 数组

								break;
							case -1:// 错误

								break;

							default:
								break;
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						dismissDialog(ID_LOADING);
					}
				}

				@Override
				public <T> void onReturnFailResult(int requestCode,
						ApiResult<T> apiResult) {

				}

				@Override
				public <T> void onReturnLoading(int requestCode) {
					showDialog(ID_LOADING);
				}
			});
			api.Login(1, username, pwd, LoginActivity.this);

			break;
		case R.id.btn_arrow:
			item.setVisibility(View.GONE);
			break;
		case R.id.btn_set:
			item.setVisibility(View.VISIBLE);
			break;

		default:
			break;
		}

	}
}
